package com.cyf.plc.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.callbacks.onPreShow
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.cyf.library.util.logi
import com.cyf.plc.R
import com.cyf.plc.base.BaseFragment
import com.cyf.plc.bean.OutAirStatus
import com.cyf.plc.bean.PlcWriteAttribute
import com.cyf.plc.bean.SystemStatus
import com.cyf.plc.constant.Constants
import com.cyf.plc.constant.Constants.Companion.ATTR_AIR_VOLUME
import com.cyf.plc.constant.Constants.Companion.ATTR_CARBON_DIOXIDE
import com.cyf.plc.constant.Constants.Companion.ATTR_FAULT
import com.cyf.plc.constant.Constants.Companion.ATTR_HUMIDITY
import com.cyf.plc.constant.Constants.Companion.ATTR_LEAVE_HOME
import com.cyf.plc.constant.Constants.Companion.ATTR_MODE
import com.cyf.plc.constant.Constants.Companion.ATTR_PM25
import com.cyf.plc.constant.Constants.Companion.ATTR_POWER
import com.cyf.plc.constant.Constants.Companion.ATTR_TEMP
import com.cyf.plc.constant.Constants.Companion.ATTR_VOC
import com.cyf.plc.constant.Constants.Companion.PLC_SUB_ATTRIBUTE_IDS
import com.cyf.plc.constant.Constants.Companion.PWD
import com.cyf.plc.constant.Constants.Companion.SYSTEM_ATTR_IDS
import com.cyf.plc.constant.Constants.Companion.SYSTEM_STATUS
import com.cyf.plc.databinding.FragmentMainBinding
import com.cyf.plc.event.PlcInitEvent
import com.cyf.plc.model.PlcAttribute
import com.cyf.plc.plc.PlcExecutor
import com.cyf.plc.ui.PlcHomeActivity
import com.cyf.plc.ui.PlcModeActivity
import com.cyf.plc.ui.SettingActivity
import com.cyf.plc.util.State
import com.cyf.plc.util.setValueText
import com.cyf.plc.util.showToast
import com.cyf.plc.viewmodel.MainViewModel
import kotlinx.android.synthetic.main.fragment_main.*
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@ExperimentalCoroutinesApi
class MainFragment : BaseFragment<MainViewModel, FragmentMainBinding>() {

    private val systemStatusLiveData = MutableLiveData<SystemStatus>()

    private val outAirStatusLiveData = MutableLiveData<OutAirStatus>()

    private val plcAttributes = ArrayList<PlcAttribute>()

    //    var vb1: Int = 3010//设备id前缀 EE
//    var vb2: Int = 3011//区号 00
//    var vb3: Int = 3012 //25
//    var vb4: Int = 3013//自定义小区编号 01
//    var vb5: Int = 3014//小区楼栋 10
//    var vb6: Int = 3015//房间号 04
//    var vb7: Int = 3016//02
    private val deviceIdAttrArray = intArrayOf(3009, 3010, 3011, 3012, 3013, 3014)

    private val deviceIdArray = intArrayOf(0, 0, 0, 0, 0, 0)

    private val systemStatus =
        SystemStatus(
            "--", "--％", 0f, 0f, 0f,
            power = true,
            leaveHome = true,
            modeStr = "未知模式",
            modeValue = 0f,
            volumeValue = 0f,
            noFault = true
        )

    override fun layoutId(): Int = R.layout.fragment_main

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getPlcInitEvent(plcInitEvent: PlcInitEvent) {
        var deviceId = ""
        for (j in deviceIdArray) {
            var subDeviceId = Integer.toHexString(j)
            if (subDeviceId.length == 1) {
                subDeviceId = "0$subDeviceId"
            }
            deviceId += subDeviceId
        }
        deviceId = "ee$deviceId"
        (deviceId + "从云请求配置").logi()
        mViewModel.requestYunConfig(deviceId)
            .observe(viewLifecycleOwner, Observer { state ->
                //获取到配置啦
                when (state) {
                    is State.Success -> {
                        val log = "获取配置成功:" + state.data
                        log.logi()
                        showToast(deviceId + "获取配置成功")
                        mViewModel.saveYunConfigs(state.data)
                    }
                }
            })
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initFragmentAfterActivityCreated()
    }

    private fun initFragmentAfterActivityCreated() {
        //加载所有属性
        getAllPlcAttributes()
        //查找系统属性
        getSystemPlcAttributes()
        //初始化故障点位
        getSystemFaultAttributes()
        //请求天气
        getCity()
        //订阅状态
        initStatus()
    }

    private fun initStatus() {
        //初始化室内状态
        systemStatusLiveData.observe(viewLifecycleOwner, Observer {
            mViewBinding.systemStatus = systemStatusLiveData.value
        })
        outAirStatusLiveData.observe(viewLifecycleOwner, Observer {
            mViewBinding.outStatus = outAirStatusLiveData.value
        })
        systemStatusLiveData.value = systemStatus
        outAirStatusLiveData.value = OutAirStatus("--", "--", "--")
    }

    private fun getSystemFaultAttributes() {
        mViewModel.getAllPlcFaultAddress().observe(viewLifecycleOwner, Observer {
            PlcExecutor.plcFaultList = it
        })
    }

    private fun getCity() {
        mViewModel.getWeather("南京", viewLifecycleOwner)
//        mViewModel.getCity().observe(viewLifecycleOwner, Observer { state ->
//            when (state) {
//                is State.Success -> {
//                    var body = state.data
//                    if (body.isNotEmpty()) {
//                        val n = body.indexOf('{')
//                        if (n >= 0) {
//                            try {
//                                body = body.substring(n, body.length - 1)
//                                "body:$body".logi()
//                                val cityInfo: CityInfo? =
//                                    moshi.adapter(CityInfo::class.java).fromJson(body)
//                                if (cityInfo != null) {
//                                    val cname = cityInfo.cname
//                                    val city = cname?.substring(cname.indexOf("省") + 1)
//                                    "cname:$cname".logi()
//                                    "city:$city".logi()
//                                    //定时请求天气
//                                    mViewModel.getWeather(city, viewLifecycleOwner)
//                                }
//                            } catch (e: JSONException) {
//                                e.printStackTrace()
//                            }
//                        }
//                    }
//                }
//            }
//        })
    }

    override fun initView() {
        "initView".logi()
        //初始化点击事件
        initClickListener()
    }

    private fun initClickListener() {
        //跳转面板房间选择
        iv_home.setOnClickListener {
            startActivity(Intent(context, PlcHomeActivity::class.java))
            activity?.overridePendingTransition(0, 0)
        }
        //跳转模式选择
        tv_mode_select.setOnClickListener {
            //跳转Fragment
//            val bundle = Bundle()
//            bundle.putParcelable(SYSTEM_STATUS, systemStatus)
//            view?.let { it1 ->
//                Navigation.findNavController(it1)
//                    .navigate(R.id.action_main_fragment_to_plc_mode_fragment, bundle)
//            }
            val intent = Intent(context, PlcModeActivity::class.java)
            intent.putExtra(SYSTEM_STATUS, systemStatus)
            startActivity(intent)
            activity?.overridePendingTransition(0, 0)
        }
        //处理电源按钮按键操作
        iv_system_power.setOnClickListener {
            val writeAttribute = PlcWriteAttribute(
                systemStatus.powerPlcAttribute.offSet,
                if (systemStatus.power)
                    systemStatus.powerOffAttribute.attributeValue else systemStatus.powerOnAttribute.attributeValue,
                systemStatus.powerPlcAttribute.addressUnit
            )
            PlcExecutor.write(writeAttribute)
        }
        //处理离家按钮按键操作
        iv_leave_home.setOnClickListener {
            val writeAttribute = PlcWriteAttribute(
                systemStatus.leaveHomePlcAttribute.offSet,
                if (systemStatus.leaveHome)
                    systemStatus.leaveHomeOffAttribute.attributeValue else systemStatus.leaveHomeOnAttribute.attributeValue,
                systemStatus.leaveHomePlcAttribute.addressUnit
            )
            PlcExecutor.write(writeAttribute)
        }
        //风量
        iv_supply_air.setOnClickListener {
            val writeAttribute = PlcWriteAttribute(
                systemStatus.volumePlcAttribute.offSet,
                if (systemStatus.volumeValue == systemStatus.volume2Attribute.attributeValue) systemStatus.volume3Attribute.attributeValue else systemStatus.volume2Attribute.attributeValue,
                systemStatus.volumePlcAttribute.addressUnit
            )
            PlcExecutor.write(writeAttribute)
        }
        //系统设置
        iv_logo.setOnClickListener {
            //弹出密码----19920823
            this.context?.let { it1 ->
                MaterialDialog(it1).show {
                    onPreShow { dialog ->
                        val passwordInput: EditText =
                            dialog.getCustomView().findViewById(R.id.password)
                        //设置初始密码
//                        passwordInput.setText(PWD)
                    }
                    setTitle("登陆")
                    customView(R.layout.dialog_password)
                    positiveButton(R.string.login) { dialog ->
                        // Pull the password out of the custom view when the positive button is pressed
                        val passwordInput: EditText =
                            dialog.getCustomView().findViewById(R.id.password)
                        if (passwordInput.text.toString() == PWD) {
                            startActivity(Intent(this.context, SettingActivity::class.java))
                        } else {
                            showToast("密码错误")
                        }
                    }
                    negativeButton(android.R.string.cancel)
                    lifecycleOwner(this@MainFragment)
                }
            }
        }
    }

    private fun getAllPlcAttributes() {
        mViewModel.getPlcAttributes().observe(viewLifecycleOwner, Observer {
            //新增读取设备id列表属性
            for (i in deviceIdAttrArray.indices) {
                val plcAttribute =
                    PlcAttribute("", deviceIdAttrArray[i], Constants.VB, "ATTR_DEVICE_ID", "设备id")
                it.add(plcAttribute)
                plcAttributes.add(plcAttribute)
            }
            PlcExecutor.plcAttributeList = it
        })
    }

    private fun getSystemPlcSubAttributes() {
        mViewModel.getPlcSubAttributes(PLC_SUB_ATTRIBUTE_IDS)
            .observe(viewLifecycleOwner, Observer { it ->
                //初始化属性
                it.forEach {
                    when (it.attributeId) {
                        //制冷 制热 通风 除湿
                        PLC_SUB_ATTRIBUTE_IDS[0] -> {
                            systemStatus.modeColdAttribute = it
                        }
                        PLC_SUB_ATTRIBUTE_IDS[1] -> {
                            systemStatus.modeHotAttribute = it
                        }
                        PLC_SUB_ATTRIBUTE_IDS[2] -> {
                            systemStatus.modeVentilationAttribute = it
                        }
                        PLC_SUB_ATTRIBUTE_IDS[3] -> {
                            systemStatus.modeDehumidifyAttribute = it
                        }

                        //开机 关机
                        PLC_SUB_ATTRIBUTE_IDS[4] -> {
                            systemStatus.powerOnAttribute = it
                        }
                        PLC_SUB_ATTRIBUTE_IDS[5] -> {
                            systemStatus.powerOffAttribute = it
                        }

                        //离家开 离家关
                        PLC_SUB_ATTRIBUTE_IDS[6] -> {
                            systemStatus.leaveHomeOnAttribute = it
                        }
                        PLC_SUB_ATTRIBUTE_IDS[7] -> {
                            systemStatus.leaveHomeOffAttribute = it
                        }

                        //风量2 风量3
                        PLC_SUB_ATTRIBUTE_IDS[10] -> {
                            systemStatus.volume2Attribute = it
                        }
                        PLC_SUB_ATTRIBUTE_IDS[11] -> {
                            systemStatus.volume3Attribute = it
                        }

                    }
                }

                PlcExecutor.read(systemStatus.powerPlcAttribute)
                PlcExecutor.read(systemStatus.modePlcAttribute)
                PlcExecutor.read(systemStatus.tempPlcAttribute)
                PlcExecutor.read(systemStatus.humidityPlcAttribute)
                PlcExecutor.read(systemStatus.vocPlcAttribute)
                PlcExecutor.read(systemStatus.carbonDioxidePlcAttribute)
                PlcExecutor.read(systemStatus.pm25PlcAttribute)
                PlcExecutor.read(systemStatus.leaveHomePlcAttribute)
                PlcExecutor.read(systemStatus.faultPlcAttribute)

                systemStatusLiveData.value = systemStatus
            })
    }

    private fun getSystemPlcAttributes() {
        mViewModel.getPlcAttributes(SYSTEM_ATTR_IDS)
            .observe(viewLifecycleOwner, Observer { it ->

                //初始化属性
                it.forEach {
                    when (it.attributeName) {
                        ATTR_MODE -> {
                            systemStatus.modePlcAttribute = it
                        }
                        ATTR_POWER -> {
                            systemStatus.powerPlcAttribute = it
                        }
                        ATTR_TEMP -> {
                            systemStatus.tempPlcAttribute = it
                        }
                        ATTR_HUMIDITY -> {
                            systemStatus.humidityPlcAttribute = it
                        }
                        ATTR_CARBON_DIOXIDE -> {
                            systemStatus.carbonDioxidePlcAttribute = it
                        }
                        ATTR_PM25 -> {
                            systemStatus.pm25PlcAttribute = it
                        }
                        ATTR_VOC -> {
                            systemStatus.vocPlcAttribute = it
                        }
                        ATTR_LEAVE_HOME -> {
                            systemStatus.leaveHomePlcAttribute = it
                        }
                        ATTR_AIR_VOLUME -> {
                            systemStatus.volumePlcAttribute = it
                        }
                        ATTR_FAULT -> {
                            systemStatus.faultPlcAttribute = it
                        }
                    }
                    //查找系统子属性
                    getSystemPlcSubAttributes()
                }
                systemStatusLiveData.value = systemStatus
            })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getOutAirStatus(outAirStatus: OutAirStatus) {
        outAirStatusLiveData.value = outAirStatus
        outAirStatus.temp?.let { setValueText(it, tv_out_room_temp, "℃") }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getPlcAttributeEvent(plcAttribute: PlcAttribute) {
        //处理设备id读取结果
        for (i in deviceIdAttrArray) {
            if (plcAttribute.offSet == i) {
                val pos = deviceIdAttrArray.indexOf(i)
                deviceIdArray[pos] = plcAttribute.value.toInt()
            }
        }
        var shouldUpdate = false
        //todo 处理plc接收到的数据
        if (plcAttribute.offSet == systemStatus.tempPlcAttribute.offSet) {
            systemStatus.temp = (plcAttribute.value / 10f).toString()
            setValueText(systemStatus.temp, tv_room_temp, "℃")
        }
        if (plcAttribute.offSet == systemStatus.humidityPlcAttribute.offSet) {
            systemStatus.humidity = (plcAttribute.value / 10f).toString()
            setValueText(systemStatus.humidity, tv_indoor_humidity, "％")
        }
        if (plcAttribute.offSet == systemStatus.carbonDioxidePlcAttribute.offSet) {
            systemStatus.carbonDioxide = plcAttribute.value
            shouldUpdate = true
        }
        if (plcAttribute.offSet == systemStatus.vocPlcAttribute.offSet) {
            systemStatus.voc = plcAttribute.value
            shouldUpdate = true
        }
        if (plcAttribute.offSet == systemStatus.pm25PlcAttribute.offSet) {
            systemStatus.pm25 = plcAttribute.value
            shouldUpdate = true
        }
        if (plcAttribute.offSet == systemStatus.volumePlcAttribute.offSet) {
            systemStatus.volumeValue = plcAttribute.value
            shouldUpdate = true
        }
        if (plcAttribute.offSet == systemStatus.faultPlcAttribute.offSet) {
            systemStatus.noFault = (plcAttribute.value == 0f)
            shouldUpdate = true
        }
        if (plcAttribute.offSet == systemStatus.leaveHomePlcAttribute.offSet) {

            when (plcAttribute.value) {
                systemStatus.leaveHomeOnAttribute.attributeValue -> {
                    //离家
                    systemStatus.leaveHome = true
                }
                systemStatus.leaveHomeOffAttribute.attributeValue -> {
                    //居家
                    systemStatus.leaveHome = false
                }
            }

            shouldUpdate = true
        }
        if (plcAttribute.offSet == systemStatus.modePlcAttribute.offSet) {
            //需要转义
            shouldUpdate = true
            systemStatus.modeValue = plcAttribute.value
            when (plcAttribute.value) {
                systemStatus.modeColdAttribute.attributeValue -> {
                    //制冷
                    systemStatus.modeStr = "制冷模式"
                }
                systemStatus.modeHotAttribute.attributeValue -> {
                    //制热
                    systemStatus.modeStr = "制热模式"
                }
                systemStatus.modeVentilationAttribute.attributeValue -> {
                    //通风
                    systemStatus.modeStr = "通风模式"
                }
                systemStatus.modeDehumidifyAttribute.attributeValue -> {
                    //除湿
                    systemStatus.modeStr = "除湿模式"
                }
            }
        }
        if (plcAttribute.offSet == systemStatus.powerPlcAttribute.offSet) {
            //需要转义
            shouldUpdate = true

            when (plcAttribute.value) {
                systemStatus.powerOnAttribute.attributeValue -> {
                    //开机
                    systemStatus.power = true
                }
                systemStatus.powerOffAttribute.attributeValue -> {
                    //关机
                    systemStatus.power = false
                }
            }
        }
        if (shouldUpdate) {
            systemStatusLiveData.value = systemStatus
        }
    }

    override fun createViewModel(): MainViewModel = activity?.run {
        ViewModelProvider(this)[MainViewModel::class.java]
    } ?: throw Exception("Invalid Activity")
}